package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.ClusterGroupEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.ClusterMapNacosPublisher
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/1
 * @description TODO
 */
@Component("clusterMapNacosPublisher")
public class ClusterMapNacosPublisher extends com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosPublisher implements DynamicRulePublisher<Set<ClusterGroupEntity>> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<Set<ClusterGroupEntity>, String> converter;

    @Override
    public void publish(String app, Set<ClusterGroupEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");

        if (rules == null) {
            return;
        }

        String ruleString = converter.convert(rules);
        // 测试Nacos连通性和配置信息
        testNacosConnectivity(app, NacosRuleConstants.CLUSTER_MAP_DATA_ID_POSTFIX);

        configService.publishConfig(app + NacosRuleConstants.CLUSTER_MAP_DATA_ID_POSTFIX, NacosRuleConstants.GROUP_ID, ruleString, ConfigType.JSON.getType());
        testPublishContent(app, NacosRuleConstants.CLUSTER_MAP_DATA_ID_POSTFIX, ruleString);
    }
}